package com.zhiyou.app.common.handler;

import cn.dev33.satoken.exception.NotLoginException;
import com.zhiyou.app.common.exception.BizException;
import com.zhiyou.app.common.exception.UnAuthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 *
 * @author jonathan.z
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理基础异常
     *
     * @param ex      异常
     * @param request 请求
     * @return 响应
     */
    @ExceptionHandler(value = BizException.class)
    public ResponseEntity<Object> handleBaseException(Exception ex, WebRequest request) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("code", "00500");
        responseBody.put("msg", ex.getMessage());
        // 返回错误响应
        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleException(Exception ex, WebRequest request) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("code", "00500");
        responseBody.put("msg", ex.getMessage().matches(".*[\\u4e00-\\u9fa5].*") ? ex.getMessage() : "系统错误，请联系管理员");
        log.error("系统错误：{}", ex.getMessage(), ex);
        // 返回错误响应
        return new ResponseEntity<>(responseBody, HttpStatus.OK);
    }

    @ExceptionHandler(value = UnAuthException.class)
    public ResponseEntity<Object> handleUnAuthException(Exception ex, WebRequest request) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("msg", ex.getMessage());
        responseBody.put("code", "401");
        // 返回错误响应
        return new ResponseEntity<>(responseBody, HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler(value = NotLoginException.class)
    public ResponseEntity<Object> NotLoginException(Exception ex, WebRequest request) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("msg", ex.getMessage());
        responseBody.put("code", "401");
        // 返回错误响应
        return new ResponseEntity<>(responseBody, HttpStatus.UNAUTHORIZED);
    }
}
